package com.alibaba.dubbo.remoting.msgcodec;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.dubbo.common.HeaderProvider2;
import com.alibaba.dubbo.common.header.HeaderProvider2Impl;
import com.alibaba.dubbo.remoting.MessageEncodeRegistry;


/**
 * 消息加密器注册
 * @author Administrator
 *
 */
public class MessageEncodeRegistryImpl extends HeaderProvider2Impl implements MessageEncodeRegistry{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	List<String> encodes = new ArrayList<String>();
	 
	public MessageEncodeRegistryImpl() {
		super();
	}

	public MessageEncodeRegistryImpl(Map<String, String> attachments) {
		super(attachments);
	}
	
	public MessageEncodeRegistryImpl(HeaderProvider2 provider) {
		super(provider);
	}

	/**
	 * 添加一个编码器
	 * @param name
	 */
	public void appendEncode(String name){
		if(encodes.isEmpty() ||  !encodes.get(encodes.size() -1).equalsIgnoreCase(name)){
			encodes.add(name);
		}
	}
	
	/**
	 * 删除一个编码器
	 * @param name
	 */
	public void removeEncode(String name){
		List<String> newEncodes = new ArrayList<String>();
		
		for(String s : encodes){
			if(!name.equalsIgnoreCase(s)){
				newEncodes.add(s);
			}
		}
		
		encodes = newEncodes;
	}
	
	public String getEncodesAsString(){
		if(encodes.isEmpty()) return null;
		StringBuilder sb = new StringBuilder();
		for(String s : encodes){
			if(sb.length() > 0){
				sb.append(",");
			}
			sb.append(s);
		}
		return sb.toString();
	}
}
